<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <div class="buttons">
      <el-button type="primary" icon="el-icon-plus" @click="add"
        >新增</el-button
      >
    </div>
    <div class="mod-result-table">
      <HTable
        ref="table"
        :tableData="tableData"
        :columnConfigs="columnConfigs"
        @selection-change="handleSelectionChange"
        :selectable="false"
        orderable
        v-loading="loading"
        :pages="pagination"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template slot-scope="{ row }">
          <template v-if="row.name == 'action'">
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="edit(row.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              size="small"
              @click="handleDelete(row.row)"
              >删除</el-button
            >
          </template>
        </template>
      </HTable>
    </div>
    <div class="vpnform">
      <el-dialog
        :title="editFlag ? '编辑规则' : '新增规则'"
        class="configDialog"
        :visible.sync="configVisible"
        :before-close="handleConfigClose"
        top="5vh"
        width="70%"
      >
        <el-form
          class="base-form"
          ref="baseForm"
          :model="baseForm"
          :rules="rules"
          auto-complete="on"
        >
          <!-- <div class="top">
            <div>规则名称:</div>
            <el-input v-model="ruleName" placeholder="请输入"></el-input>
          </div> -->
          <el-form-item label="规则名称：" prop="ruleName" label-width="90px">
            <el-input
              v-model="baseForm.ruleName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-table
            ref="table-input"
            class="table"
            border
            :header-cell-style="{
              background: '#F5F5F5',
              color: '#333',
            }"
            stripe
            height="350"
            highlight-current-row
            :data="baseForm.demoList"
          >
            <el-table-column label="匹配键" show-overflow-tooltip>
              <template slot="header" slot-scope="scope">
                <div><span class="star">*</span>匹配键</div>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'demoList.' + scope.$index + '.matchKey'"
                  :rules="rules.matchKey"
                  class="all"
                >
                  <el-select
                    v-model="scope.row.matchKey"
                    filterable
                    placeholder="请选择"
                    collapse-tags
                    clearable
                    @focus="
                      $refs.baseForm.clearValidate(
                        `demoList.${scope.$index}.matchKey`
                      )
                    "
                  >
                    <el-option
                      v-for="item in configKeysListFilter"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <template v-slot:error>--</template>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="匹配类型" show-overflow-tooltip>
              <template slot="header" slot-scope="scope">
                <div><span class="star">*</span>匹配类型</div>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'demoList.' + scope.$index + '.matchType'"
                  :rules="rules.matchType"
                  class="all"
                >
                  <el-select
                    v-model="scope.row.matchType"
                    filterable
                    placeholder="请选择"
                    collapse-tags
                    clearable
                    @focus="
                      $refs.baseForm.clearValidate(
                        `demoList.${scope.$index}.matchType`
                      )
                    "
                  >
                    <el-option
                      v-for="item in configList"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <template v-slot:error>--</template>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="匹配值" show-overflow-tooltip>
              <template slot="header" slot-scope="scope">
                <div><span class="star">*</span>匹配值</div>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'demoList.' + scope.$index + '.matchValue'"
                  :rules="rules.matchValue"
                  class="all"
                >
                  <el-input
                    v-model.trim="scope.row.matchValue"
                    placeholder="请输入"
                    clearable
                    @focus="
                      $refs.baseForm.clearValidate(
                        `demoList.${scope.$index}.matchValue`
                      )
                    "
                  ></el-input>
                  <template v-slot:error>--</template>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" @click="deleteDomain(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-form-item style="margin-top: 10px; margin-bottom: 0">
            <el-button @click="addDomain">新增配置项</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="configVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitConfigForm('addform')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import table from "@/mixins/commontable";
import { columnConfigs } from "./columnConfigs.js";
import { addList, editList, getList, delCurRow } from "@/api/yybl/jinkurule";
import config from "./config";
export default {
  components: {},
  mixins: [table, config], //表格的混入，主要包括表格上通用的方法和数据，比如查询，重置，分页这些功能
  props: {},
  data() {
    let checkTransparency = (rex, value, callback) => {
      // if (!value) {
      //   return callback(new Error('年龄不能为空'));
      // }
      // const rule = new RegExp("^0.\d$");
      const rule = /^0.\d+$/;
      if (rule.test(value) || value == 0 || value == 1) {
        callback();
      } else {
        callback(new Error("透明度范围为0-1"));
      }
    };
    let checkNumber = (rex, value, callback) => {
      // if (!value) {
      //   return callback(new Error('年龄不能为空'));
      // }
      // const rule = new RegExp("^0.\d$");
      const rule = /^\d*$/;
      if (rule.test(value)) {
        callback();
      } else {
        callback(new Error("请输入数字"));
      }
    };
    return {
      columnConfigs,
      configVisible: false,
      editFlag: false,
      fontOptions: [
        {
          value: "微软雅黑",
          label: "微软雅黑",
        },
        {
          value: "宋体",
          label: "宋体",
        },
        {
          value: "仿宋",
          label: "仿宋",
        },
        {
          value: "黑体",
          label: "黑体",
        },
        {
          value: "楷体",
          label: "楷体",
        },
        {
          value: "等线",
          label: "等线",
        },
      ],
      vpnform: {
        // rotation: new Number(),
        // size: new Number(),
      },
      rulesVpnform: {
        size: [
          { validator: checkNumber, trigger: "blur" },
          // { required: false, message: "大小不能为空" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        rotation: [
          { validator: checkNumber, trigger: "blur" },
          // { required: false, message: "角度不能为空" },
          // { type: "number", message: "角度必须为数字值" },
        ],
        width: [
          { validator: checkNumber, trigger: "blur" },
          // { required: false, message: "大小不能为空" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        height: [
          { validator: checkNumber, trigger: "blur" },
          // { required: false, message: "大小不能为空" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        transparency: [{ validator: checkTransparency, trigger: "blur" }],
      },
      computers: [],
      vpntypes: [],
      curRow: {},
    };
  },
  watch: {},
  computed: {
    configKeysListFilter() {
      return this.configKeysList.filter(
        (item) =>
          this.baseForm.demoList.map((i) => i.matchKey).indexOf(item.value) ==
          -1
      );
    },
  },
  methods: {
    add() {
      this.editFlag = false;
      this.$nextTick(() => {
        this.configVisible = true;
        this.$refs?.baseForm?.clearValidate();
      });
      this.baseForm.ruleName = "";
      this.baseForm.demoList.splice(0);
      this.baseForm.demoList.push({
        matchType: "",
        matchKey: "",
        matchValue: "",
      });
    },
    edit(row) {
      this.editFlag = true;
      this.curRow = row;
      this.handleConfig(row);
    },
    async handleDelete(row) {
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let ids;
          if (row) ids = row.ruleId;
          const res = await delCurRow({
            ids: ids,
          });
          if (res.rescode == "200") {
            this.$message.success("删除成功");
            this.refresh();
          } else this.$message.error(res.msg);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitaddForm(val) {
      console.log(val);
      this.$refs["addform"].validate((val) => {
        if (val) {
          console.log("通过校验");
          const {
            host,
            content,
            size,
            rotation,
            font,
            color,
            width,
            height,
            transparency,
          } = this.vpnform;
          let params = {
            host,
            content,
            size,
            rotation,
            font,
            color,
            width,
            height,
            transparency,
          };
          // params.userId = null;
          // params.sharedkey = encode(form.sharedkey);
          if (this.editFlag) {
            params.watermarkId = this.curRow.watermarkId;
            editList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.configVisible = false;
                  this.$message.success("编辑成功");
                  this.refresh();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            // 调用新增接口
            addList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.configVisible = false;
                  this.$message.success("新增成功");
                  this.refresh();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          console.log("校验失败");
        }
      });
    },
    handleClose() {
      this.configVisible = false;
    },
    handleSelectionChange() {},
    refresh() {
      this.getlists(getList, {});
    },
  },
  created() {
    this.refresh();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  .el-date-editor.el-input {
    width: 100%;
  }
}
::v-deep .el-button {
  .el-icon-edit + span {
    margin-left: 0px;
  }
  .el-icon-delete + span {
    margin-left: 0px;
  }
}
::v-deep .el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }
  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }
}
.base-form {
  .top {
    display: flex;
    align-items: center;
    div:nth-child(1) {
      width: 80px;
      text-align: right;
      margin-right: 3px;
    }
  }
  ::v-deep .el-table {
    .el-table__body {
      .el-table__cell {
        padding: 0 0;
        height: 38px !important;
      }
    }
    .el-form-item--small.el-form-item {
      margin: 0px 0;
    }
    .star {
      color: #f56c6c;
    }
  }
}
</style>
